package com.shierke.Ume.ui.adapter.me

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.shierke.Ume.R
import com.shierke.Ume.util.click
import kotlinx.android.synthetic.main.item_setting_photo.view.*

/**
 * Create by Ybx
 * on 2020-10-18
 * Desribe:
 */
class SettingPhotoAdapter(
    var addCallBack: () -> Unit,
    var longTouchListener: (holder: RecyclerView.ViewHolder) -> Unit
) :
    RecyclerView.Adapter<SettingPhotoAdapter.ViewHolder>() {


    private var phototList = arrayListOf<String>()


    fun getPhotoList() = phototList


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.item_setting_photo, null, false)
        return ViewHolder(view)
    }

    override fun getItemCount() = if (phototList.size < 6) phototList.size + 1 else 6

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        holder.onBind(position)
    }


    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun onBind(position: Int) {
            with(itemView) {

                rootViews.click {
                    if (position >= phototList.size) {
                        addCallBack()
                    }
                }


                var photoUrl = ""
                if (position < phototList.size) {
                    photoUrl = phototList[position]
                }

                if (!TextUtils.isEmpty(photoUrl)) {
                    Glide.with(context)
                        .load(photoUrl)
                        .into(image)
                    dele.visibility = View.VISIBLE

                    rootViews.setOnLongClickListener {
                        longTouchListener(this@ViewHolder)
                        return@setOnLongClickListener true
                    }

                } else {
                    image.setImageBitmap(null)
                    dele.visibility = View.GONE

                    rootViews.setOnLongClickListener {
                        return@setOnLongClickListener false
                    }
                }


                dele.click {

                    if (phototList.size > position) {
                        phototList.removeAt(position)
                        notifyDataSetChanged()
                    }

                }

            }
        }
    }
}